﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DIProject.Stock
{	public partial class ShiftIn : Form
	{	private	Util.ActionType actionType;
		private	ShiftsIn shiftsIn;
//-------------------------------------------------------------------------------------------------
		private	DIProject.DataSets.Stock shiftsInStock{get{return shiftsIn != null? shiftsIn.stock: null;}}
		private	DIProject.DataSets.StockTableAdapters.ShiftsInTableAdapter shiftsInTableAdapter{get{return shiftsIn != null? shiftsIn.shiftsInTableAdapter: null;}}
		private	DIProject.DataSets.Stock.ShiftsInRow shiftsInRow = null;
		private	int docId{get{return shiftsInRow != null? shiftsInRow.Id: 0;}}
		private	string docNumber{get{return shiftsInRow != null? shiftsInRow.DocNumber: Properties.Resources.strUndefined;}}
		private	string docDate{get{return shiftsInRow != null? shiftsInRow.DocDate.ToString("d"): Properties.Resources.strUndefined;}}
		private decimal sum
		{	get
			{	object s = stock.ShiftInLines.Compute("sum(RetailSum)", null);
				return s is decimal? (decimal)s: 0m;
			}
		}
//-------------------------------------------------------------------------------------------------
		public ShiftIn() : this(Util.ActionType.NoAction, null)
		{
		}

		public ShiftIn(Util.ActionType actionType, ShiftsIn shiftsIn)
		{	InitializeComponent();
			stock.Init();
			textFormat = Text;
			this.actionType	= actionType;
			this.shiftsIn	= shiftsIn;
			toolStripButtonUpdate.Enabled = false;
			toolStripButtonDelete.Enabled = false;
			if(	actionType == DIProject.Util.ActionType.Update
			&&	shiftsIn != null
			&&	shiftsIn.shiftsInGridView.CurrentCell != null)
				shiftsInRow = (DIProject.DataSets.Stock.ShiftsInRow)((DataRowView)shiftsIn.shiftsInGridView.CurrentCell.OwningRow.DataBoundItem).Row;
		}
//-------------------------------------------------------------------------------------------------
		private readonly string textFormat;
		private void SetCaption()
		{	Text = string.Format
			(	textFormat
			,	docNumber
			,	docDate
			,	sum.ToString("N2")
			);
		}
//-------------------------------------------------------------------------------------------------
		private void ShiftIn_Load(object sender, EventArgs e)
		{	Binding binding;
			try
			{	departmentsTableAdapter.Fill(dictionary.Departments);
				switch(actionType)
				{	case DIProject.Util.ActionType.Insert:
						shiftsInRow = shiftsInStock.ShiftsIn.NewShiftsInRow();
						shiftsInRow.DocDate	= DateTime.Today;
						shiftsInRow.MD		= DateTime.Now;
						shiftsInRow.MW		= FirstForm.Login;
						shiftsInStock.ShiftsIn.AddShiftsInRow(shiftsInRow);
						goto case DIProject.Util.ActionType.Update;
					case DIProject.Util.ActionType.Update:
						shiftInPartiesTableAdapter.Fill(stock.ShiftInParties, docId);
						shiftInLinesTableAdapter.Fill(stock.ShiftInLines, docId);
						comboBoxDepartment.DataBindings.Add("SelectedValue", shiftsInRow, "DepartmentId");
						textBoxNote.DataBindings.Add("Text", shiftsInRow, "Note");
						binding = new Binding("Text", shiftsInRow, "ContragentDocDateStr");
						binding.Format += new ConvertEventHandler(nullableDateTimeFormat_Format);
						textBoxOutDocDate.DataBindings.Add(binding);
						textBoxOutDocNumber.DataBindings.Add("Text", shiftsInRow, "ContragentDocNumber");
						break;
				}
			}
			catch(SqlException eq)
			{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		//	buttonChiceOutDoc.Enabled = actionType == DIProject.Util.ActionType.Insert;
			SetCaption();
		}
		private void nullableDateTimeFormat_Format(object sender, ConvertEventArgs e)
		{	if(e.DesiredType == typeof(string))
				e.Value	=	e.Value is DateTime
						?	((DateTime)e.Value).ToString("d")
						:		e.Value is string
							?	(	((string)e.Value).Length > 10
								?	((string)e.Value).Substring(0, 10)
								:	(string)e.Value
								)
							:	string.Empty
						;
		}
//-------------------------------------------------------------------------------------------------
		private void ShiftIn_FormClosing(object sender, FormClosingEventArgs e)
		{	BindingManagerBase bindingManager = BindingContext[shiftsInRow];
			if(bindingManager != null)
				bindingManager.EndCurrentEdit();
			int		delLines	= 0//stock.ShiftInLines	.Select(null, null, DataViewRowState.Deleted			).Length
				,	insLines	= 0//stock.ShiftInLines	.Select(null, null, DataViewRowState.Added				).Length
				,	modLines	= stock.ShiftInLines	.Select(null, null, DataViewRowState.ModifiedCurrent	).Length
				,	modParties	= stock.ShiftInParties	.Select(null, null, DataViewRowState.ModifiedCurrent	).Length
				;
			if(shiftsInRow.RowState != DataRowState.Unchanged
			|| delLines > 0
			|| insLines > 0
			|| modLines > 0
			|| modParties > 0)
				switch(MessageBox.Show
					(	this
					,	Properties.Resources.strDocIsChanged
					,	Properties.Resources.strConfirmation
					,	MessageBoxButtons.YesNoCancel
					,	MessageBoxIcon.Question
					,	MessageBoxDefaultButton.Button1
					)
				)
				{	case DialogResult.Yes:
						toolStripButtonSave_Click(toolStripButtonSave, EventArgs.Empty);
						delLines	= 0;//stock.ShiftInLines	.Select(null, null, DataViewRowState.Deleted			).Length;
						insLines	= 0;//stock.ShiftInLines	.Select(null, null, DataViewRowState.Added				).Length;
						modLines	= stock.ShiftInLines	.Select(null, null, DataViewRowState.ModifiedCurrent	).Length;
						modParties	= stock.ShiftInParties	.Select(null, null, DataViewRowState.ModifiedCurrent	).Length;
						if(shiftsInRow.RowState != DataRowState.Unchanged
						|| delLines > 0
						|| insLines > 0
						|| modLines > 0
						|| modParties > 0)
							e.Cancel = true;
						break;
					case DialogResult.No:
						shiftsInRow.RejectChanges();
						stock.ShiftInLines.RejectChanges();
						stock.ShiftInParties.RejectChanges();
						break;
					case DialogResult.Cancel:
						e.Cancel = true;
						break;
				}
		}
//-------------------------------------------------------------------------------------------------
		private void ShiftIn_Resize(object sender, EventArgs e)
		{	int width = panelHeader.ClientSize.Width - labelDepartment.Left - comboBoxDepartment.Left;
			comboBoxDepartment.	Width = width;
			textBoxNote.		Width = width;
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
//		private void buttonChiceOutDoc_Click(object sender, EventArgs e)
//		{	ShiftsOutFree shiftsOutFree = new ShiftsOutFree();
//			if(shiftsOutFree.ShowDialog(this) == DialogResult.OK)
//			{	shiftsInRow.ContragentDocDate	= shiftsOutFree.DocDate;
//				shiftsInRow.ContragentDocNumber	= shiftsOutFree.DocNumber;
//				BindingManagerBase bindingManager = BindingContext[shiftsInRow];
//				if(bindingManager != null)
//				{	bindingManager.EndCurrentEdit();
//					bindingManager.ResumeBinding();
//				}
//			}
//		}
//-------------------------------------------------------------------------------------------------
		private void toolStripButtonRefresh_Click(object sender, EventArgs e)
		{	try
			{	departmentsTableAdapter.Fill(dictionary.Departments);
				stock.EnforceConstraints = false;
				shiftInLinesTableAdapter.Fill(stock.ShiftInLines, docId);
				shiftInPartiesTableAdapter.Fill(stock.ShiftInParties, docId);
				stock.EnforceConstraints = true;
			}
			catch(SqlException eq)
			{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			SetCaption();
		}
//-------------------------------------------------------------------------------------------------
		private void toolStripButtonSave_Click(object sender, EventArgs e)
		{	try
			{	BindingManagerBase bindingManager = BindingContext[shiftsInRow];
				if(bindingManager != null)
					bindingManager.EndCurrentEdit();
				linesGridView.EndEdit();
				int		insLines = 0//stock.ShiftInLines.Select(null, null, DataViewRowState.Added		).Length
					,	delLines = 0//stock.ShiftInLines.Select(null, null, DataViewRowState.Deleted	).Length
					;
				shiftsInTableAdapter.Update(shiftsInRow);					// Заголовок документа
				shiftInPartiesTableAdapter.Update(stock.ShiftInParties);	// Партии
				shiftInLinesTableAdapter.Update(stock.ShiftInLines);		// Строки документа
				stock.EnforceConstraints = false;
				shiftInPartiesTableAdapter.Fill(stock.ShiftInParties, docId);
				stock.EnforceConstraints = true;
				shiftsInRow.DepartmentName	= comboBoxDepartment.Text;
				shiftsInRow.Lines			= shiftsInRow.Lines + insLines - delLines;
				shiftsInRow.DocSum			= sum;

				shiftsInRow.AcceptChanges();
				SetCaption();
			}
			catch(SqlException eq)
			{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
//-------------------------------------------------------------------------------------------------
		private void linesGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
		{	if(e.RowIndex >= 0 && linesGridView.Columns[e.ColumnIndex] == qnttyDataGridViewTextBoxColumn)
				SetCaption();
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
		private void toolStripButtonUnblock_Click(object sender, EventArgs e)
		{	DIProject.DataSets.Stock.ShiftInLinesRow row;
			for(int i = 0, n = stock.ShiftInLines.Count; i < n; ++i)
			{	row = stock.ShiftInLines[i];
				if(row.Blocked)
					row.Blocked = false;
			}
		}
//-------------------------------------------------------------------------------------------------
		private void toolStripButtonBlock_Click(object sender, EventArgs e)
		{	DIProject.DataSets.Stock.ShiftInLinesRow row;
			for(int i = 0, n = stock.ShiftInLines.Count; i < n; ++i)
			{	row = stock.ShiftInLines[i];
				if(!row.Blocked)
					row.Blocked = true;
			}
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
	}
}